using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Text;
using System.Windows.Forms;
using Meebey.SmartIrc4net;

namespace dotIRC
{
    public partial class StatusForm : Form
    {
        MainForm _parent;
        TreeNode _treeNode;

        public IrcSession irc;

        delegate void ircListener();
        
        public StatusForm()
        {
            irc = new IrcSession(this);
            InitializeComponent();

            irc.SendDelay = 200;    // Give a little chance to the server....
            irc.ActiveChannelSyncing = true;

            FormClosing += new FormClosingEventHandler(StatusForm_FormClosing);
        }

/*       We tried to implement the gradient using the Paint event, but it was too glitchy.
 * 
 *       void tableLayoutPanelConnectBtn_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                e.Graphics.FillRectangle(new LinearGradientBrush(
                    ClientRectangle, SystemColors.Control, Color.FromArgb(128, 200, 255), LinearGradientMode.Vertical
                    ), e.ClipRectangle);
            }
            catch { }
        }

        void tableLayoutPanelInfo_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                e.Graphics.FillRectangle(new LinearGradientBrush(
                    ClientRectangle, SystemColors.Control, Color.FromArgb(128, 200, 255), LinearGradientMode.Vertical
                    ), e.ClipRectangle);
            }
            catch { }
        }

        void StatusForm_Paint(object sender, PaintEventArgs e)
        {
            try
            {
                e.Graphics.FillRectangle(new LinearGradientBrush(
                    ClientRectangle, SystemColors.Control, Color.FromArgb(128, 200, 255), LinearGradientMode.Vertical
                    ), e.ClipRectangle);
            }
            catch { }
        }*/

        private void StatusForm_Load(object sender, EventArgs e)
        {
            _parent = (MainForm)MdiParent;
            _treeNode = _parent.windowListTreeView.Nodes.Add(Text);
            _parent.treeViewForms.Add(_treeNode, this);
        }

        void StatusForm_FormClosing(object sender, FormClosingEventArgs e)
        {
            switch (e.CloseReason)
            {
                case CloseReason.ApplicationExitCall:
                case CloseReason.FormOwnerClosing:
                case CloseReason.MdiFormClosing:
                    irc.RfcQuit("Client exited");
                    break;
                case CloseReason.TaskManagerClosing:
                    irc.RfcQuit("Client terminated");
                    break;
                case CloseReason.WindowsShutDown:
                    irc.RfcQuit("System shutdown");
                    break;
                case CloseReason.UserClosing:
                default:
                    irc.RfcQuit();
                    break;
            }
        }

        public TreeNode TreeNode
        {
            get
            {
                return _treeNode;
            }
        }

        private void StatusForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            _parent.windowListTreeView.Nodes.Remove(_treeNode);
        }

        private void StatusForm_Activated(object sender, EventArgs e)
        {
            _parent.windowListTreeView.Select();
            _parent.windowListTreeView.SelectedNode = _treeNode;
        }

        private void linkServers_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            new ServerListForm().Show(this);
        }

        private void linkLabelPassword_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            if (textBoxPasswd.Visible)
            {
                linkLabelPassword.Text = "NickServ password:";
                textBoxPasswd.Visible = false;
                textBoxNickservPass.Visible = true;
            }
            else
            {
                linkLabelPassword.Text = "Server password:";
                textBoxNickservPass.Visible = false;
                textBoxPasswd.Visible = true;
            }
        }

        private void buttonConnect_Click(object sender, EventArgs e)
        {
            if (!irc.IsConnected)
            {
                if (comboServer.Text == "")
                {
                    MessageBox.Show("No server specified.", "Connection failure");
                    return;
                }
                if (comboNickname.Text == "")
                {
                    MessageBox.Show("No nickname specified.", "Connection failure");
                    return;
                }

                string[] serverString = comboServer.Text.Split(new char[1]{':'});
                string serverAddress = serverString[0];
                int serverPort;
                if (serverString.Length > 1)
                    serverPort = int.Parse(serverString[1]);
                else
                    serverPort = 6667;
                string realname;
                if (textBoxRealname.Text != "")
                    realname = textBoxRealname.Text;
                else
                    realname = ".IRC User";
                string nickname = comboNickname.Text;
                string password = textBoxPasswd.Text;

                // Connect us to the server
                do
                {
                    try
                    {
                        irc.Connect(serverAddress, serverPort);
                        break;
                    }
                    catch (ConnectionException ex)
                    {
                        DialogResult action = MessageBox.Show(ex.Message, "Connection failure",
                            MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);

                            if(action==DialogResult.Cancel)
                                return;
                    }
                } while (true);

                irc.Login(nickname, realname, 0, nickname, password);

                // Now that we said hello to the server, listen for what he has to say.
                new ircListener(irc.Listen).BeginInvoke(null, null);

                buttonConnect.Text = "Disconnect";

                irc.OnConnectionError += new EventHandler(irc_OnConnectionError);
                irc.OnDisconnected += new EventHandler(irc_OnDisconnected);
            }
            else
            {
                irc.RfcQuit();
            }
        }

        void irc_OnDisconnected(object sender, EventArgs e)
        {
            if (InvokeRequired)
                BeginInvoke(new EventHandler(irc_OnDisconnected), new object[] { sender, e });
            else
                buttonConnect.Text = "Connect";
        }

        void irc_OnConnectionError(object sender, EventArgs e)
        {
                DialogResult action = MessageBox.Show("Lost connection to server.", "Connection error",
                    MessageBoxButtons.RetryCancel, MessageBoxIcon.Error);
                if (action == DialogResult.Retry)
                {
                    irc.Connect(irc.Address, irc.Port);
                    irc.Login(irc.Nickname, irc.Realname, irc.IUsermode, irc.Username, irc.Password);
                    irc.Listen();       // Should be called by ircListener's thread.
                }
        }
    }
}